#include <iostream>
#include <cstring>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
  int pipefd[2];
  pipe(pipefd);

  pid_t id = fork();
  if(id < 0)
  {
    perror("create child process fail\n");
    return 0;
  }
  if(id == 0)
  {
    // child
    close(pipefd[0]); // 关闭读端接口
    const char* str = "i am a subprocess, and my pid is: ";
    //int i = 0;
    //char c = 'c';
    while(true)
    {
      char wbuffer[1024];
      sprintf(wbuffer, "%s%d", str, getpid());
      printf("向文件中开始写入\n");
      write(pipefd[1], wbuffer, strlen(wbuffer));
      printf("已经向文件中写入\n");
     // write(pipefd[1], &c, sizeof(c));
     // printf("向文件中写入%d次\n", i++);
      sleep(1);
    }
    exit(0);
  }

   // father
  close(pipefd[1]); // 关闭写端文件
  close(pipefd[0]);
//  while(1)
//  {
//    char rbuffer[1024];
//    printf("开始读取文件\n");
//    ssize_t n = read(pipefd[0], rbuffer, sizeof(rbuffer) - 1);
//    rbuffer[n] = '\0';
//    printf("%s           %d\n", rbuffer, n);
//    printf("读取文件\n");
//    sleep(1);
//  }
//  //sleep(1000);
  int status = 0;
  int wret = waitpid(id, &status, 0);
  printf("%d\n", status&0x7F);

  return 0;
}
